var websocket = null;
var param = "";

function login(data) {
    if ("" === data || data == null){
        alert("用户名不能为空");
        return false;
    }else {
        $.ajax({
            url:"/login",
            data:{"username":data},
            type:"get",
            success:function (res) {
                param = res;
                window.open("/index/"+res);
            }
        })
    }
}

function conectWebSocket(data){
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket'in window) {
        websocket = new WebSocket("ws://"+window.location.host+"/websocket/"+data);
    } else {
        alert('Not support websocket')
    }
    //连接发生错误的回调方法
    websocket.onerror = function() {
        console.error("websocket发送错误")
    };
    //连接成功建立的回调方法
    websocket.onopen = function(event) {
        console.log("websocket连接成功");
        setMessageInnerHTML(data,"大家好，我是"+data);
        param = data;
    };
    //接收到消息的回调方法
    websocket.onmessage = function(event) {
        setMessageInnerHTML(event.data.split(":")[0],event.data.split(":")[1]);
    };
    //连接关闭的回调方法
    websocket.onclose = function() {
        setMessageInnerHTML(param,"下次再聊");
    };
    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function() {
        websocket.close();
    }
}

//将消息显示在网页上
function setMessageInnerHTML(user,innerHTML) {
    var content =  document.getElementById('content-pane');
    var el = "  <li style=\"margin-top: 5px\">\n" +
        "                        <span style=\"font-weight: 600\">"+user+"</span>\n" +
        "                        <span class=\"chat-content-list\">"+innerHTML+"</span>\n" +
        "                    </li>";
    content.innerHTML = content.innerHTML + el;
}

//关闭连接
function closeWebSocket() {
    websocket.close();
}

//发送消息
function send(data) {
    var message = document.getElementById('text').value;
    if (message==="" || message ==null){
        return;
    } else {
        $.ajax({
            url:"/send",
            data:{"content":message,"user":data},
            type:'get',
            contentType:"application/json;charset=UTF-8",
            success:function (res) {
                document.getElementById('text').value = ""
            }
        })
    }

}
